package com.sagereal.soundrecorder.audio;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.Gravity;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.PopupMenu;

import com.sagereal.soundrecorder.R;
import com.sagereal.soundrecorder.bean.AudioBean;
import com.sagereal.soundrecorder.databinding.ActivityAudioListBinding;
import com.sagereal.soundrecorder.utils.AudioInfoUtils;
import com.sagereal.soundrecorder.utils.Contants;
import com.sagereal.soundrecorder.utils.DialogUtils;
import com.sagereal.soundrecorder.utils.RenameDialog;

import java.io.File;
import java.io.FilenameFilter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class AudioListActivity extends AppCompatActivity {
    private ActivityAudioListBinding binding;
    private List<AudioBean> mDates;
    private AudioListAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityAudioListBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 为ListView设置数据源和适配器
        mDates = new ArrayList<>();
        adapter = new AudioListAdapter(this,mDates);
        binding.audioLv.setAdapter(adapter);
        //加载数据
        loadDatas();
        //设置监听事件
        setEvents();
    }

    /**
     * 设置监听
     */
    private void setEvents() {
        adapter.setOnItemPlayClickListener(playClickListener);
        binding.audioLv.setOnItemLongClickListener(longClickListener);
    }
    AdapterView.OnItemLongClickListener longClickListener = new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            showPopMenu(view,position);
            return false;
        }
    };

    /*长按没一项item能够iy弹出menu窗口*/
    private void showPopMenu(View view, int position) {
        PopupMenu popupMenu = new PopupMenu(this, view, Gravity.RIGHT);
        MenuInflater menuInflater = popupMenu.getMenuInflater();
        menuInflater.inflate(R.menu.audio_menu,popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()){
                    case R.id.menu_info:
                        break;
                    case R.id.menu_del:
                        deleteFileByPos(position);
                        break;
                    case R.id.menu_rename:
                        showRenameDialog(position);
                        break;
                }
                return false;
            }
        });
        popupMenu.show();
    }

    /**
     * 显示重命名的对话框
     * @param position
     */
    private void showRenameDialog(int position) {
        AudioBean bean = mDates.get(position);
        String title = bean.getTitle();
        RenameDialog dialog = new RenameDialog(this);
        dialog.show();
        dialog.setDialogWidth();
        dialog.setTipText(title);
        dialog.setOnEnsureListener(new RenameDialog.OnEnsureListener() {
            @Override
            public void onEnsure(String msg) {
                renameByPosition(msg,position);
            }
        });
    }

    /*
    * 重命名文件名称的方法
    * */
    private void renameByPosition(String msg, int position) {
        AudioBean audioBean = mDates.get(position);
        if (audioBean.getTitle().equals(msg)) {
            return;
        }
        String path = audioBean.getPath();
        String fileSuffix = audioBean.getFileSuffix();
        File srcFile = new File(path); //原来的文件
        //获取修改路径
        String destPath = srcFile.getParent() + File.separator + msg + fileSuffix;
        File destFile = new File(destPath);
        //物理进行重命名操作
        srcFile.renameTo(destFile);
        //修改内存中的文件名
        audioBean.setTitle(msg);
        audioBean.setPath(destPath);
        adapter.notifyDataSetChanged();

    }

    /**
     * 删除指定位置的文件
     * @param position
     */
    private void deleteFileByPos(int position) {
        AudioBean bean = mDates.get(position);
        String title = bean.getTitle();
        String path = bean.getPath();
        DialogUtils.showNormalDialog(this, "提示信息", "删除文件后将无法回复，是否确定删除指定文件?", "确定", new DialogUtils.OnLeftClickListener() {
            @Override
            public void onLeftClick() {
                File file = new File(path);
                file.getAbsoluteFile().delete(); //物理删除文件
                mDates.remove(bean); //将文件从集合只删除
                adapter.notifyDataSetChanged();
            }
        }, "取消", null);

    }

    /**
     * 点击每一个播放按钮会回调的方法
     */
    AudioListAdapter.OnItemPlayClickListener playClickListener = new AudioListAdapter.OnItemPlayClickListener() {
        @Override
        public void onItemPlayClick(AudioListAdapter adapter, View convertView, View playView, int position) {

        }
    };
    private void loadDatas() {
        //获取指定路径下的音频文件
        File fetchFile = new File(Contants.PATH_FETCH_DIR_RECORD);
        File[] listFiles= fetchFile.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                if (new File(dir,name).isDirectory()) {
                    return false;
                }
                if (name.endsWith(".aac") || name.endsWith(".amr")) {
                    return true;
                }
                return false;
            }
        });

        SimpleDateFormat adf = new SimpleDateFormat("yyyy/MM/dd");
        AudioInfoUtils audioInfoUtils = AudioInfoUtils.getInstance();
        // 遍历数组中的文件，依次得到文件信息
        for (int i = 0; i < listFiles.length; i++) {
            File audioFile = listFiles[i];
            String fname = audioFile.getName();  //文件名带了后缀
            String title = fname.substring(0, fname.lastIndexOf(".")); //substring包前不包后
            String suffix = fname.substring(fname.lastIndexOf("."));
            //获取文件最后修改的时间
            long flastMod = audioFile.lastModified();
            String time = adf.format(flastMod); //转换成对应格式的时间字符串
            //获取文件的字节数
            long flength = audioFile.length();
            //获取文件的路径
            String audioPath = audioFile.getAbsolutePath();
            long duration = audioInfoUtils.getAudioFileDuration(audioPath);
            String formatDuration = audioInfoUtils.getAudioFileFormatDuration(duration);
            AudioBean audioBean = new AudioBean(i + "", title, time, formatDuration, audioPath,
                    duration, flastMod, suffix, flength);
            mDates.add(audioBean);
        }
        audioInfoUtils.releaseRetriever(); //释放对媒体资料的资源对象
        //将集合中的元重新排序，按照时间排序
        Collections.sort(mDates, new Comparator<AudioBean>() {
            @Override
            public int compare(AudioBean o1, AudioBean o2) {
                if (o1.getLastModified()< o2.getLastModified()) {
                    return 1; //调换顺序,最新修改的在前面
                }else if (o1.getLastModified()==o2.getLastModified()){
                    return 0;
                }
                return -1;
            }
        });
        adapter.notifyDataSetChanged();
    }
}